package cn.acewill.yxd.yunxundian.ui.user;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jimmy.common.util.ToastUtils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.TodayTaskrecycleAdapter;
import cn.acewill.yxd.yunxundian.componet.CheckDataDialog;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.componet.menology.month.OnMonthClickListener;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.SignUpInfo;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.AsynData;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.pubClass.signuppanel;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.follow_up.FollowUpActivity;
import cn.acewill.yxd.yunxundian.ui.schedule.ScheduleActivity;
import cn.acewill.yxd.yunxundian.ui.sign.EditEvaluationActivity;
import cn.acewill.yxd.yunxundian.ui.sign.EvaluationMianActivity;
import cn.acewill.yxd.yunxundian.ui.sign.MyEvaluationActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SendMailActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SignActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SignInActivity;
import cn.acewill.yxd.yunxundian.ui.sign.SignMainActivity;
import cn.acewill.yxd.yunxundian.ui.sign.WrittingEvaluationListActivity;
import cn.acewill.yxd.yunxundian.utils.DensityUtil;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

//import cn.acewill.yxd.yunxundian.ui.sign.EditEvaluationActivity;

/**
 * Created by AAA on 2017/4/6.
 */

public class FirstPageFragment extends Fragment implements View.OnClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private DataProvider dp=new DataProvider();
    private RecyclerView myTaskList;
    private TextView totalTaskNum;
    private TextView userSign;
    private TextView titleView;
    public  int schId=-1;
    public static int myschid=0;
    /*listview的数据源*/
    private   List<Schedule> toDaySch;
    private SignUpInfo signUpInfo;
    protected Shop thisShop;
    private LinearLayout nodata;
    public Employee thisEmp;
    private SwipeRefreshLayout pullFresh;
    LinearLayoutManager manager;
    private final Handler mhadler = new MyHandler(this);
    private int firstItem,lastItem;
    private boolean needMove;
    private int movePosition;

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View myview = inflater.inflate(R.layout.main_fragment, container, false);
        initView(myview);
        initRecycle();
        LoadLocalData();
        return myview;
    }

    public void initRecycle(){
        manager=new LinearLayoutManager(getContext());
        myTaskList.setLayoutManager(manager);
        myTaskList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (needMove){
                    needMove = false;
                    int n = movePosition - firstItem;
                    if (n<=0&&n<myTaskList.getChildCount()){
                        int top = myTaskList.getChildAt(n).getTop();
                        myTaskList.scrollTo(0,top);
                    }
                }
            }
        });


        //不显示
      //  myTaskList.addItemDecoration(new RecyclerViewDivider(getContext(),LinearLayoutManager.VERTICAL));
    }

    public void shopSignIntent(Schedule schedule)
    {
        Intent in=new Intent(getContext(),SignActivity.class);
        myschid=schedule.getID();
        in.putExtra("rrschid",schedule.getID());
        startActivityForResult(in,100);
    }

    public void initView(View view) {
        toDaySch = dp. getScheduleTask(MainActivity.id);
        signUpInfo=dp.getSignupInfo(MainActivity.id);
        this.userSign =  view.findViewById(R.id.userSign);
        this.userSign.setOnClickListener(this);
        TextView userSchedule =  view.findViewById(R.id.userSchedule);
        userSchedule.setOnClickListener(this);
        TextView evaluation =  view.findViewById(R.id.evaluation);
        evaluation.setOnClickListener(this);
        TextView follow_up =  view.findViewById(R.id.follow_up);
        follow_up.setOnClickListener(this);
        pullFresh =  view.findViewById(R.id.pullFresh);
        pullFresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //判断网络状态
                if (NetWorkStateReceiver.whetherConnectNetWork==1){
                    new Thread(runnable).start();
                }else{
                    Toast.makeText(getContext(),"无网络连接",Toast.LENGTH_SHORT).show();
                    if (pullFresh.isRefreshing()) pullFresh.setRefreshing(false);
                }
            }
        });
        this.myTaskList =  view.findViewById(R.id.myTaskList);
        this.totalTaskNum =  view.findViewById(R.id.totalTaskNum);
        this.titleView = view.findViewById(R.id.textView);
        this.nodata = view.findViewById(R.id.nodata);
        if (toDaySch == null) {
            totalTaskNum.setText("至今未完成的任务(0)");
            nodata.setVisibility(View.VISIBLE);
        } else {
            totalTaskNum.setText("至今未完成的任务(" + toDaySch.size() + ")");
            nodata.setVisibility(View.GONE);
        }
        if(signUpInfo!=null)
        {
            MainActivity.signId=signUpInfo.get_ID();
            this.userSign.setText("签出");
            thisShop=dp.getShopinfo(signUpInfo.getShopId());
            if(thisShop!=null) {
                this.titleView.setText(thisShop.getShopName());
            }
        }
        else
        {
            MainActivity.signId=0;
            this.userSign.setText("签到");
            this.titleView.setText("云巡店");
        }
        try {
            thisEmp=db.selector(Employee.class).where("ID","=",MainActivity.id+"").findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }

    }


    private static class MyHandler  extends Handler{

        private final WeakReference<FirstPageFragment> mActivity;

        MyHandler(FirstPageFragment activity) {
            mActivity = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                mActivity.get().LoadLocalData();
                if ( mActivity.get().pullFresh.isRefreshing()){
                    Toast.makeText(mActivity.get().getContext(),"刷新成功",Toast.LENGTH_SHORT).show();
                    mActivity.get().pullFresh.setRefreshing(false);
                }
            }
        }
    }
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            AsynData asynData = new AsynData(mhadler);
            try {
                int value = asynData.asynScheduleData(MainActivity.id);
                Message msg = new Message();
                msg.what = value;
                mhadler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.userSign:
                if(signUpInfo==null) {
                    startActivityForResult(new Intent(getContext(), SignMainActivity.class),101);
                }
                else{
                    thisShop=dp.getShopinfo(signUpInfo.getShopId());
                    if(thisShop!=null) {
                        Intent in = new Intent(getContext(), SignInActivity.class);
                        in.putExtra("ycol", thisShop.getyCol());
                        in.putExtra("xcol", thisShop.getxCol());
                        in.putExtra("shopId", thisShop.getID());
                        in.putExtra("shopName", thisShop.getShopName());
                        in.putExtra("checktype","out");
                        in.putExtra("signid",signUpInfo.get_ID());
                        startActivityForResult(in,101);
                    }
                    else
                        Toast.makeText(getContext(), "门店不存在或已被禁用", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.userSchedule:
                startActivityForResult(new Intent(getContext(),ScheduleActivity.class),103);
                break;
            case R.id.evaluation:
//                Intent intent=new Intent(getContext(), EvaluationMianActivity.class);
//                /*此处评估页面只查询完成的状态，传递标识进行判断*/
//                intent.putExtra("lable",1);
//                startActivityForResult(intent,104);
                Intent intent = new Intent(getContext(), MyEvaluationActivity.class);
                startActivityForResult(intent,104);
                break;
            case R.id.follow_up:
                startActivityForResult(new Intent(getContext(),FollowUpActivity.class),107);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 101:
            case 100:
            case 102:
            case 103:
            case 104:
            case 105:
            case 106:
            case 107:
                LoadLocalData();
                break;
        }
    }

    public void kaishirenwu(Schedule bean)
    {
//        Schedule thisSch = null;
//        try {
//            thisSch = db.selector(Schedule.class).where("ID","=",bean.getID()).findFirst();
//            sType thisSt=db.selector(sType.class).where("ID","=",thisSch.getSTypeID()).findFirst();
//            //TODO 空值问题
//            reportId=thisSt.getReportId();
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
        schId=bean.getID();
//        Intent in=new Intent(getContext(), WrittingEvaluationListActivity.class);
//        in.putExtra("rrschid",schId);
//        startActivityForResult(in,105);
        Intent in=new Intent(getContext(), EditEvaluationActivity.class);
        in.putExtra("schId",schId);
        startActivityForResult(in,105);
    }


    //endregion
    public void LoadLocalData(){
        signUpInfo=dp.getSignupInfo(MainActivity.id);
        if(signUpInfo!=null) {
            this.userSign.setText("签出");
            Shop thisShop=dp.getShopinfo(signUpInfo.getShopId());
            if(thisShop!=null) {
                this.titleView.setText(thisShop.getShopName());
            }
        }
        else
        {
            this.userSign.setText("签到");
            this.titleView.setText("云巡店");
        }

        toDaySch=dp.getScheduleTask(MainActivity.id);
        if(toDaySch==null){
            nodata.setVisibility(View.VISIBLE);
            totalTaskNum.setText("至今未完成的任务(0)");
        }
        else{
            nodata.setVisibility(View.GONE);
            totalTaskNum.setText("至今未完成的任务("+toDaySch.size()+")");
        }
        TodayTaskrecycleAdapter adapter = new TodayTaskrecycleAdapter(getContext(), toDaySch, new TodayTaskrecycleAdapter.moreTaskCallBack() {
            @Override
            public void Click(Schedule bean) throws DbException {
                kaishirenwu(bean);
            }
            @Override
            public void submitClick(Schedule bean) {
                checkData(bean);
            }
            @Override
            public void shopSignClick(Schedule bean) {
                shopSignIntent(bean);
            }

            @Override
            public void onScorller(int position) {
                setRecycleScroller(position);

            }
        }, thisEmp);
        myTaskList.setAdapter(adapter);
        int ff = manager.findFirstVisibleItemPosition();
        int ll = manager.findLastVisibleItemPosition();
        Log.e("ff",ff+","+ll);
    }

    private void setRecycleScroller(final int position){

        //屏幕的第一个position 与最后一个position
        myTaskList.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                myTaskList.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                firstItem = manager.findFirstVisibleItemPosition();
                lastItem = manager.findLastVisibleItemPosition();
                Log.e("setRecycleScroller","first:"+firstItem+",last:"+lastItem+","+"pos:"+position);
                int center = (lastItem - firstItem)/2;
                if (position>center){  //大于初始值
                    if (firstItem+center<position){
                        if (position == toDaySch.size()-1){
                            myTaskList.smoothScrollToPosition(position+1);
                        }else{
                            myTaskList.scrollToPosition(position+1);
                        }
                        movePosition = position+1;
                        needMove = true;
                    } else {
                        myTaskList.smoothScrollToPosition(position-1);
                    }
                }
            }
        });
    }






    public  void checkData(Schedule sch){
        schId=sch.getID();
        try{
            Schedule thisSch=db.selector(Schedule.class).where("ID","=",schId+"").findFirst();
            if(thisSch.getStates()>1) {
                boolean[] falg = CheckDataDialog.getInstance(getContext()).checkDataComplete(schId);
                if (falg!=null){
                    showTipDialog(falg);
                }else{
                    BaseActivity.showToast(getContext(),"数据错误");
                }

            }else{
                BaseActivity.showAnimaDialog(getContext(),"请先执行任务");
            }
        }catch (DbException e) {
            e.printStackTrace();
        }
    }


    private void showTipDialog(boolean[] need){
        if (!need[0]&&!need[1]&&!need[2]){
            startActivity(new Intent(getContext(),SendMailActivity.class).putExtra("schId",schId));
        }else{
            final Dialog dialog= new Dialog(getContext(),R.style.mydialog);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.eva_check_dialog, (ViewGroup) getActivity().getWindow().getDecorView(),false);
            TextView addFollow = view.findViewById(R.id.addFollow);
            TextView shopSign = view.findViewById(R.id.shopSign);
            TextView jiBenData = view.findViewById(R.id.jiBenData);
            TextView gotoSubmit = view.findViewById(R.id.gotoSubmit);
            gotoSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startActivityForResult(new Intent(getContext(),SendMailActivity.class).putExtra("schId",schId),106);
                }
            });
            TextView cancel_action = view.findViewById(R.id.cancel_action);
            cancel_action.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    startActivityForResult(new Intent(getContext(),EditEvaluationActivity.class).putExtra("schId",schId),105);
                }
            });
            if (!need[0]){
                addFollow.setVisibility(View.GONE);
            }
            if (!need[1]){
                shopSign.setVisibility(View.GONE);
            }
            if (!need[2]){
                jiBenData.setVisibility(View.GONE);
            }
            dialog.setContentView(view);
            dialog.setCancelable(true);
            dialog.show();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消handler消息队列  If null, all callbacks and messages will be removed.
        mhadler.removeCallbacksAndMessages(null);
    }
}